import { CodeCollapse } from '../CodeCollapse.js'

const templateCode = `<v-crud
  :table-config="tableConfig"
  :search-bar-config="searchBarConfig"
  :create-and-update-config="createAndUpdateConfig"
/>`

export const BasicUsage = {
  template: `
    <el-card header="基本的增删改查" ref="container">
      ${templateCode}
      <CodeCollapse :codes="[templateCode, scriptCode]" />
    </el-card>
  `,

  components: {
    CodeCollapse
  },

  data() {
    const tableData = [{
      date: '2016-05-02',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1518 弄',
      id: 1
    }, {
      date: '2016-05-04',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1517 弄',
      id: 2
    }, {
      date: '2016-05-01',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1519 弄',
      id: 3
    }, {
      date: '2016-05-03',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1516 弄',
      id: 4
    }]
    const editDataApi = (data) => {
      console.log(data, 'data');
      return new Promise(r => {
        setTimeout(r, 1000)
      })
    }
    const deleteApi = (data) => {
      console.log(data, 'data');
      return new Promise(r => {
        setTimeout(r, 1000)
      })
    }

    return {
      // 表格配置
      tableConfig: {
        requestApi(query) {
          console.log(query); // 包括页数、条数在内的查询参数
          return new Promise(r => {
            setTimeout(() => {
              r({
                data: tableData,
                count: 3,
                pageSize: 20,
                pages: 1
              })
            }, 800)
          })
        },
        delete: data => deleteApi({ id: data.id }),
        columns: [
          { label: '日期', prop: 'date' },
          { label: '姓名', prop: 'name' },
          { label: '地址', prop: 'address' }
        ]
      },

      // 搜索栏配置
      searchBarConfig: {
        items: [
          'address',
          { column: 'name' },
          { column: 'date', component: 'date' }
        ]
      },

      // 增加和编辑的配置
      createAndUpdateConfig: {
        items: [
          { column: 'name', required: true },
          { column: 'address', component: 'textarea', required: true },
          { label: '备注', prop: 'remark', component: 'textarea' }
        ],
        create(data) {
          return editDataApi(data)
        },
        update(data, row) {
          data.id = row.id
          return editDataApi(data)
        }
      }
    }
  },

  computed: {
    templateCode() {
      return `<template>
  ${templateCode}
</template>`
    },
    scriptCode() {
      const { data } = BasicUsage
      return `<script>
export default {
  ${data.toString()}
}
</script>`
    }
  },
}